// src/components/core/CartItemFc.tsx
import { Button, Image, Input } from 'antd'
import React, { ChangeEvent, FC, useState } from 'react'
import { API } from '../../config'
import { CartItem, deleteItem, updateItem } from '../../helpers/cart'

interface Props {
    product: CartItem
    setCart: (arg: CartItem[]) => void
}

const CartItemFc: FC<Props> = ({ product, setCart }) => {
    const [count, setCount] = useState<number>(product.count)
    const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
        let count = parseInt(event.target.value)
        // 更新父组件购物车中的数据
        setCart(updateItem(product._id, count))
        setCount(count)
    }
    return (
        <tr className="ant-table-row">
            <th className="ant-table-cell">
                <Image width={120} src={`${API}/product/photo/${product._id}`} />
            </th>
            <th className="ant-table-cell">{ product.name }</th>
            <th className="ant-table-cell">{ product.price }</th>
            <th className="ant-table-cell">{ product.category.name }</th>
            <th className="ant-table-cell">
                <Input type="number" value={ count } onChange={handleChange} />
            </th>
            <th className="ant-table-cell">
                <Button 
                    danger 
                    type="primary" 
                    onClick={() => setCart(deleteItem(product._id))}
                >删除</Button>
            </th>
        </tr>
    )
}

export default CartItemFc